<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/utils/request'
import type { HomeSection } from '@/constants/HOME'

// 接收父级 v-model，用于切换到 FAQ
const currentSection = defineModel<HomeSection>({ required: false })

const searchText = ref('')
const notices = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 详情弹窗状态
const showDetail = ref(false)
const detailLoading = ref(false)
const detailError = ref('')
const detailItem = ref<any>(null)

// 获取公告列表
const fetchNotices = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: currentPage.value.toString(),
      limit: pageSize.value.toString()
    })
    if (searchText.value.trim()) {
      params.append('q', searchText.value.trim())
    }

    const response = await api.get(`/api/content/notices?${params}`)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const data = await response.json()
    const { items, total: totalCount } = data

    notices.value = items
    total.value = totalCount
  } catch (error) {
    console.error('공지사항 목록 가져오기 실패:', error)
    notices.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchNotices()
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

async function openDetail(id: string | number) {
  showDetail.value = true
  detailLoading.value = true
  detailError.value = ''
  detailItem.value = null
  try {
      const res = await api.get(`/api/content/notices/${id}`)
    if (!res.ok) throw new Error(await res.text())
    detailItem.value = await res.json()
  } catch (e: any) {
    detailError.value = e?.message || '로딩 실패'
  } finally {
    detailLoading.value = false
  }
}

onMounted(() => {
  fetchNotices()
})
</script>

<template>
  <div class="notice-panel">
    <div class="header">
      <div class="tabs">
        <button class="tab" @click="currentSection && (currentSection = 'faq' as any)">자주 묻는 질문</button>
        <button class="tab active">공지사항</button>
      </div>
      <div class="search-bar">
        <input
          v-model.trim="searchText"
          placeholder="검색어 입력 (엔터로 검색)"
          @keyup.enter="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">🔍</button>
      </div>
    </div>

    <div class="content">
      <div class="stats">총 {{ total }}개</div>

      <div v-if="loading" class="loading">로딩 중...</div>

      <div v-else-if="notices.length === 0" class="empty">
        공지사항이 없습니다
      </div>

      <div v-else class="notice-list">
        <div v-for="notice in notices" :key="notice.id" class="notice-item clickable" :class="{ pinned: notice.isPinned }" @click="openDetail(notice.id)">
          <div class="badge" :class="{ pinned: notice.isPinned }">
            {{ notice.isPinned ? '고정' : '공지' }}
          </div>
          <div class="main">
            <div class="title-row">
              <div class="title">{{ notice.title }}</div>
              <div class="date">{{ formatDate(notice.createdAt) }}</div>
            </div>
            <div class="subtitle">
              <span class="capsule" :class="{ neutral: !notice.category }">{{ notice.category || '공식 공지' }}</span>
            </div>
            <div class="meta">
              <span class="author">공식</span>
              <span class="dot">·</span>
              <span class="m-hint">클릭하여 자세히 보기</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 详情弹窗 -->
      <div v-if="showDetail" class="detail-mask" @click.self="showDetail = false">
        <div class="detail-modal">
          <div class="detail-header">
            <div class="title">{{ detailItem?.title || '상세 정보' }}</div>
            <button class="close" @click="showDetail = false">✕</button>
          </div>
          <div class="detail-body">
            <div v-if="detailLoading" class="loading">로딩 중...</div>
            <div v-else-if="detailError" class="error">{{ detailError }}</div>
            <template v-else>
              <div class="meta">
                <span class="badge" :class="{ pinned: detailItem?.isPinned }">{{ detailItem?.isPinned ? '고정' : '공지' }}</span>
                <span class="date">{{ detailItem?.createdAt ? formatDate(detailItem.createdAt) : '' }}</span>
              </div>
              <div class="content">{{ detailItem?.content }}</div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.notice-panel {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-4);
}

.tabs {
  display: flex;
  gap: var(--space-2);
}

.tab {
  height: 40px;
  padding: 0 var(--space-4);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
  background: var(--color-surface);
  color: var(--color-text-secondary);
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.tab:hover {
  background: var(--color-surface-hover);
  border-color: var(--color-primary);
}

.tab.active {
  border-color: var(--color-primary);
  background: var(--color-primary-light);
  color: var(--color-primary);
}

.search-bar {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  min-width: 280px;
}

.search-bar input {
  flex: 1;
  background: transparent;
  border: 0;
  color: var(--color-text);
  outline: 0;
  font-size: 14px;
}

.search-bar input::placeholder {
  color: var(--color-text-muted);
}

.search-btn {
  background: transparent;
  border: 0;
  color: var(--color-text-secondary);
  cursor: pointer;
  padding: var(--space-1);
  border-radius: var(--radius-sm);
  transition: all 0.2s ease;
}

.search-btn:hover {
  background: var(--color-surface);
  color: var(--color-primary);
}

.content {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  box-shadow: var(--shadow-sm);
}

.stats {
  color: var(--color-text-secondary);
  margin-bottom: var(--space-3);
  font-size: 14px;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.notice-item {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  padding: var(--space-4);
  background: var(--color-surface);
  border: 1px solid var(--color-border-light);
  border-radius: var(--radius-lg);
  transition: all 0.2s ease;
}

.notice-item.pinned {
  border-color: var(--color-warning);
  background: rgba(245, 158, 11, 0.05);
}

.notice-item.clickable {
  cursor: pointer;
}

.notice-item.clickable:hover {
  background: var(--color-surface-hover);
  box-shadow: var(--shadow-md);
  transform: translateY(-1px);
  border-color: var(--color-border);
}

.badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  color: var(--color-text-white);
  background: var(--color-text-secondary);
  flex: 0 0 auto;
}

.badge.pinned {
  background: var(--color-warning);
}

.main {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  justify-content: space-between;
}

.title {
  color: var(--color-text);
  font-weight: 600;
  margin-bottom: var(--space-1);
}

.date {
  color: var(--color-text-muted);
  font-size: 12px;
}

.subtitle {
  margin-top: var(--space-1);
}

.capsule {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding: 0 var(--space-2);
  border-radius: 999px;
  background: var(--color-primary-light);
  border: 1px solid var(--color-border);
  color: var(--color-primary);
  font-size: 12px;
  font-weight: 500;
}

.capsule.neutral {
  background: var(--color-surface);
  color: var(--color-text-muted);
}

.meta {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  color: var(--color-text-muted);
  font-size: 12px;
  margin-top: var(--space-1);
}

.meta .dot {
  opacity: 0.5;
}

.author {
  color: var(--color-primary);
  font-weight: 500;
}

/* 详情弹窗样式 */
.detail-mask {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.detail-modal {
  width: min(800px, 90vw);
  max-height: 80vh;
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-xl);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-xl);
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-4) var(--space-5);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-surface);
}

.detail-header .title {
  color: var(--color-text);
  font-weight: 700;
  font-size: 18px;
}

.detail-header .close {
  background: transparent;
  border: 0;
  color: var(--color-text-muted);
  cursor: pointer;
  padding: var(--space-2);
  border-radius: var(--radius-sm);
  font-size: 18px;
  transition: all 0.2s ease;
}

.detail-header .close:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
}

.detail-body {
  padding: var(--space-5);
  overflow: auto;
}

.detail-body .meta {
  display: flex;
  gap: var(--space-3);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-4);
}

.detail-body .badge {
  background: var(--color-text-secondary);
  color: var(--color-text-white);
  border-radius: 999px;
  padding: var(--space-1) var(--space-2);
  font-size: 12px;
  font-weight: 600;
}

.detail-body .badge.pinned {
  background: var(--color-warning);
}

.detail-body .content {
  white-space: pre-wrap;
  line-height: 1.8;
  color: var(--color-text);
}

.detail-body .content p {
  margin: 0 0 var(--space-3);
}

.detail-body .content code {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  padding: var(--space-1);
  font-family: 'Monaco', 'Menlo', monospace;
}

.loading,
.empty {
  text-align: center;
  color: var(--color-text-muted);
  padding: var(--space-6) 0;
  font-size: 16px;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
  .notice-panel {
    gap: var(--space-4);
  }

  /* 让头部纵向堆叠并占满宽度 */
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: var(--space-3);
  }

  .tabs {
    width: 100%;
    gap: var(--space-2);
  }

  /* 允许按钮文字换行并自适应高度 */
  .tab {
    height: auto;
    min-height: 36px;
    white-space: normal;
    line-height: 1.2;
    text-align: center;
    padding: var(--space-2) var(--space-2);
  }

  .tabs .tab {
    flex: 1 1 0;
  }

  .search-bar {
    width: 100%;
    min-width: 0;
    flex-direction: row;
    gap: var(--space-2);
  }

  .search-input {
    width: 100%;
  }

  .notice-item {
    padding: var(--space-3);
    gap: var(--space-3);
  }

  .notice-content h3 {
    font-size: 16px;
  }

  .notice-content p {
    font-size: 13px;
  }

  .notice-meta {
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .notice-panel {
    gap: var(--space-3);
  }

  .header {
    gap: var(--space-2);
  }

  .tabs {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--space-2);
    width: 100%;
  }

  .tab {
    padding: var(--space-2) var(--space-3);
    font-size: 13px;
  }

  .search-bar {
    width: 100%;
    min-width: 0;
    gap: var(--space-2);
  }

  .search-bar input {
    padding: var(--space-3);
    font-size: 14px;
  }

  .notice-list {
    gap: var(--space-2);
  }

  .notice-item {
    padding: var(--space-3);
    gap: var(--space-3);
  }

  .badge {
    width: 28px;
    height: 28px;
    font-size: 10px;
    flex-shrink: 0;
  }

  .main {
    min-width: 0; /* 允许内容收缩 */
  }

  .title-row {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--space-1);
  }

  .title {
    font-size: 14px;
    font-weight: 600;
    line-height: 1.3;
    white-space: normal;
    word-break: break-word;
  }

  .date {
    font-size: 11px;
    color: var(--color-text-muted);
    align-self: flex-end;
  }

  .subtitle {
    margin-top: var(--space-1);
    gap: var(--space-1);
  }

  .capsule {
    font-size: 10px;
    padding: 2px var(--space-1);
  }

  .stats {
    font-size: 13px;
    margin-bottom: var(--space-3);
  }

  /* 可选：移动端减少杂讯 */
  .m-hint {
    display: none;
  }
}
</style>
